import {View, Text, Platform, StyleSheet, StatusBar} from 'react-native';
import React from 'react';
import {useSafeAreaInsets} from 'react-native-safe-area-context';

const NAV_BAR_HEIGHT_IOS = 44; //导航栏在IOS中的高度
const NAV_BAR_HEIGHT_ANDROID = 50; //导航栏在Android中的高度

export default function NavigationBar({
  style = {},
  title,
  titleView,
  titleLayoutStyle = {},
  rightButton,
  leftButton,
  hide,
  statusBarOpts = {
    barStyle: 'light-content',
    hidden: false,
  },
}) {
  const insets = useSafeAreaInsets();

  const getButtonElement = data => {
    return <View style={styles.navBarButton}>{data ? data : null}</View>;
  };

  //导航栏中间显示的内容
  const titleContent = titleView ? (
    titleView
  ) : (
    <Text ellipsizeMode={'head'} numberOfLines={1} style={styles.title}>
      {title}
    </Text>
  );

  //导航栏(左边按钮+中间显示+右边按钮)
  const content = hide ? null : (
    <View style={styles.navBar}>
      {getButtonElement(leftButton)}
      <View style={[styles.navBarTitleContainer, titleLayoutStyle]}>
        {titleContent}
      </View>
      {getButtonElement(rightButton)}
    </View>
  );

  //渲染状态栏与导航栏
  return (
    <View
      style={[
        styles.container,
        {
          paddingTop: insets.top,
        },
        style,
      ]}>
      {statusBarOpts.hidden ? null : <StatusBar {...statusBarOpts} />}
      {content}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#2196f3',
  },
  navBarButton: {
    alignItems: 'center',
  },
  title: {
    fontSize: 20,
    color: '#ffffff',
  },
  navBar: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    height: Platform.OS === 'ios' ? NAV_BAR_HEIGHT_IOS : NAV_BAR_HEIGHT_ANDROID,
    paddingLeft: 10,
    paddingRight: 10,
  },
  navBarTitleContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    position: 'absolute',
    paddingLeft: 4,
    left: 40,
    right: 40,
    top: 0,
    bottom: 0,
  },
});
